package cn.le.service;

import cn.le.dao.DeviceDAO;
import cn.le.dto.DeviceDTO;
import cn.le.po.DevicePO;
import cn.le.redis.BaseRedisUtil;
import cn.le.util.BeanUtils;
import cn.le.util.IdUtils;
import cn.le.vo.RedisDeviceVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class DeviceService {

    @Autowired
    private DeviceDAO deviceDAO;
    @Autowired
    private BaseRedisUtil redisUtil;

    @Transactional(rollbackFor = Exception.class)
    public void add(DeviceDTO dto){
        DevicePO po = deviceDAO.getByName(dto.getProductId(),dto.getName());
        if (po != null){
            throw new RuntimeException("名称重复");
        }
        po = deviceDAO.getByImei(dto.getImei());
        if (po != null){
            throw new RuntimeException("imei重复");
        }
        po = BeanUtils.copyProperties(DevicePO.class,dto);
        po.setId(IdUtils.next());
        po.setCreateAt(new Date());
        deviceDAO.insert(po);

        redisUtil.put(po.getImei(),new RedisDeviceVO(po));
    }

}
